<!-- views/Versions.vue -->
<template>
  <div class="versions-container">
    <el-page-header @back="router.go(-1)" class="page-header">
      <template #content>
        <div class="page-header-content">
          <el-icon class="header-icon"><Histogram /></el-icon>
          <span class="header-title">模型版本管理</span>
        </div>
      </template>
    </el-page-header>

    <!-- 版本筛选区 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="模型类型">
          <el-select v-model="filterForm.modelType" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="全局模型" value="global" />
            <el-option label="客户端模型" value="client" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 版本列表 -->
    <el-card class="versions-list">
      <template #header>
        <div class="versions-list-header">
          <span>版本历史</span>
          <el-button type="primary" size="small" @click="showUploadDialog">
            <el-icon><Upload /></el-icon>
            <span>上传模型</span>
          </el-button>
        </div>
      </template>

      <el-table
          :data="versionsData"
          style="width: 100%"
          @row-click="handleRowClick"
          class="versions-table"
      >
        <el-table-column prop="version" label="版本号" width="120">
          <template #default="{ row }">
            <el-tag :type="row.isCurrent ? 'success' : ''">
              {{ row.version }}
              <el-icon v-if="row.isCurrent" class="current-icon"><Select /></el-icon>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'global' ? 'primary' : 'info'">
              {{ row.type === 'global' ? '全局模型' : '客户端模型' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accuracy" label="准确率" width="120">
          <template #default="{ row }">
            {{ row.accuracy }}%
          </template>
        </el-table-column>
        <el-table-column prop="loss" label="损失值" width="120" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click.stop="showVersionDetail(row)">详情</el-button>
            <el-button
                size="small"
                type="danger"
                @click.stop="handleDelete(row)"
                v-if="!row.isCurrent"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pagination"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </el-card>

    <!-- 版本详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="`模型版本详情 - ${selectedVersion?.version}`"
        width="80%"
    >
      <div v-if="selectedVersion" class="version-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>基本信息</span>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="版本号">{{ selectedVersion.version }}</el-descriptions-item>
                <el-descriptions-item label="类型">
                  <el-tag :type="selectedVersion.type === 'global' ? 'primary' : 'info'">
                    {{ selectedVersion.type === 'global' ? '全局模型' : '客户端模型' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ selectedVersion.createdAt }}</el-descriptions-item>
                <el-descriptions-item label="创建者">{{ selectedVersion.creator || '系统自动生成' }}</el-descriptions-item>
                <el-descriptions-item label="文件大小">{{ selectedVersion.fileSize }}</el-descriptions-item>
                <el-descriptions-item label="哈希值">
                  <el-tooltip :content="selectedVersion.hash" placement="top">
                    <span class="hash-value">{{ selectedVersion.hash.substring(0, 8) }}...</span>
                  </el-tooltip>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <el-card class="mt-4">
              <template #header>
                <span>性能指标</span>
              </template>
              <div class="metrics-container">
                <div class="metric-item">
                  <div class="metric-label">准确率</div>
                  <div class="metric-value">{{ selectedVersion.accuracy }}%</div>
                  <el-progress
                      :percentage="selectedVersion.accuracy"
                      :color="accuracyColor(selectedVersion.accuracy)"
                      :show-text="false"
                  />
                </div>
                <div class="metric-item">
                  <div class="metric-label">损失值</div>
                  <div class="metric-value">{{ selectedVersion.loss }}</div>
                  <el-progress
                      :percentage="100 - selectedVersion.loss * 20"
                      :color="lossColor(selectedVersion.loss)"
                      :show-text="false"
                      status="exception"
                  />
                </div>
                <div class="metric-item">
                  <div class="metric-label">F1分数</div>
                  <div class="metric-value">{{ selectedVersion.f1Score || '0.82' }}</div>
                  <el-progress
                      :percentage="(selectedVersion.f1Score || 0.82) * 100"
                      color="#67C23A"
                      :show-text="false"
                  />
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card>
              <template #header>
                <span>训练指标趋势</span>
              </template>
              <line-chart :data="versionMetrics" />
            </el-card>

            <el-card class="mt-4">
              <template #header>
                <span>模型比较</span>
              </template>
              <el-select
                  v-model="compareVersion"
                  placeholder="选择要比较的版本"
                  class="compare-select"
              >
                <el-option
                    v-for="item in versionsData"
                    :key="item.version"
                    :label="item.version"
                    :value="item.version"
                    :disabled="item.version === selectedVersion.version"
                />
              </el-select>
              <div v-if="compareVersion" class="comparison-result">
                <el-table :data="comparisonData" border>
                  <el-table-column prop="metric" label="指标" width="120" />
                  <el-table-column prop="current" label="当前版本" />
                  <el-table-column prop="compare" :label="`版本 ${compareVersion}`" />
                  <el-table-column prop="diff" label="差异">
                    <template #default="{ row }">
                      <span :class="row.diffClass">{{ row.diff }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-else class="empty-comparison">
                <el-empty description="请选择一个版本来进行比较" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="mt-4">
          <template #header>
            <span>模型描述</span>
          </template>
          <div class="version-description">
            {{ selectedVersion.description || '暂无描述信息' }}
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
            type="primary"
            @click="deployVersion(selectedVersion)"
            v-if="!selectedVersion.isCurrent"
        >
          部署此版本
        </el-button>
      </template>
    </el-dialog>

    <!-- 上传模型对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传模型" width="50%">
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="模型文件" required>
          <el-upload
              class="upload-demo"
              drag
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .pth, .h5, .pt 格式的模型文件，大小不超过500MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="uploadForm.version" placeholder="例如: v1.0.0" />
        </el-form-item>
        <el-form-item label="模型类型">
          <el-radio-group v-model="uploadForm.type">
            <el-radio label="global">全局模型</el-radio>
            <el-radio label="client">客户端模型</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述信息">
          <el-input
              v-model="uploadForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入模型描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload">确认上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Histogram, Upload, Select, UploadFilled } from '@element-plus/icons-vue'
import LineChart from '@/components/charts/LineCharts.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()

// 筛选表单
const filterForm = ref({
  modelType: '',
  dateRange: [] as [Date, Date] | []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 原始版本数据
const rawVersionsData = ref([
  {
    version: 'v2.1.0',
    type: 'global',
    accuracy: 92.5,
    loss: 0.32,
    f1Score: 0.91,
    createdAt: '2023-06-15 14:30',
    description: '优化后的全局模型，准确率提升3%',
    isCurrent: true,
    creator: 'admin',
    fileSize: '45.6MB',
    hash: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
  },
  {
    version: 'v2.0.1',
    type: 'client',
    accuracy: 89.3,
    loss: 0.45,
    f1Score: 0.88,
    createdAt: '2023-06-10 09:15',
    description: '客户端A的本地优化模型',
    isCurrent: false,
    creator: 'client_A',
    fileSize: '42.1MB',
    hash: 'b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7'
  },
  {
    version: 'v2.0.0',
    type: 'global',
    accuracy: 89.5,
    loss: 0.48,
    f1Score: 0.87,
    createdAt: '2023-06-05 16:45',
    description: '初始全局模型',
    isCurrent: false,
    creator: 'system',
    fileSize: '44.8MB',
    hash: 'c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8'
  },
  {
    version: 'v1.2.3',
    type: 'client',
    accuracy: 85.7,
    loss: 0.62,
    f1Score: 0.83,
    createdAt: '2023-05-28 11:20',
    description: '客户端B的本地优化模型',
    isCurrent: false,
    creator: 'client_B',
    fileSize: '41.5MB',
    hash: 'd4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9'
  },
  {
    version: 'v1.2.2',
    type: 'global',
    accuracy: 87.2,
    loss: 0.55,
    f1Score: 0.85,
    createdAt: '2023-05-20 10:10',
    description: '修复梯度爆炸问题',
    isCurrent: false,
    creator: 'admin',
    fileSize: '43.9MB',
    hash: 'e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0'
  }
])

// 计算过滤后的版本数据
const filteredVersionsData = computed(() => {
  let result = [...rawVersionsData.value]

  // 按模型类型过滤
  if (filterForm.value.modelType) {
    result = result.filter(item => item.type === filterForm.value.modelType)
  }

  // 按时间范围过滤
  if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
    const [start, end] = filterForm.value.dateRange
    const startTime = start.getTime()
    const endTime = end.getTime()

    result = result.filter(item => {
      const itemTime = new Date(item.createdAt).getTime()
      return itemTime >= startTime && itemTime <= endTime
    })
  }

  return result
})

// 计算分页后的版本数据
const versionsData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredVersionsData.value.slice(start, end)
})

// 计算总数
const total = computed(() => filteredVersionsData.value.length)

// 版本详情对话框
const detailDialogVisible = ref(false)
const selectedVersion = ref<any>(null)
const compareVersion = ref('')
const uploadDialogVisible = ref(false)

// 上传表单
const uploadForm = ref({
  file: null,
  version: '',
  type: 'global',
  description: ''
})

// 版本指标数据
const versionMetrics = computed(() => ({
  accuracy: generateRandomData(selectedVersion.value?.accuracy / 100 || 0.8, 0.1, 10),
  loss: generateRandomData(selectedVersion.value?.loss / 2 || 0.4, 0.2, 10)
}))

// 比较数据
const comparisonData = computed(() => {
  if (!compareVersion.value || !selectedVersion.value) return []

  const compare = rawVersionsData.value.find(v => v.version === compareVersion.value)
  if (!compare) return []

  return [
    {
      metric: '准确率',
      current: `${selectedVersion.value.accuracy}%`,
      compare: `${compare.accuracy}%`,
      diff: `${(selectedVersion.value.accuracy - compare.accuracy).toFixed(2)}%`,
      diffClass: selectedVersion.value.accuracy > compare.accuracy ? 'positive' : 'negative'
    },
    {
      metric: '损失值',
      current: selectedVersion.value.loss,
      compare: compare.loss,
      diff: (selectedVersion.value.loss - compare.loss).toFixed(4),
      diffClass: selectedVersion.value.loss < compare.loss ? 'positive' : 'negative'
    },
    {
      metric: 'F1分数',
      current: selectedVersion.value.f1Score || '0.82',
      compare: compare.f1Score || '0.82',
      diff: ((selectedVersion.value.f1Score || 0.82) - (compare.f1Score || 0.82)).toFixed(4),
      diffClass: (selectedVersion.value.f1Score || 0.82) > (compare.f1Score || 0.82) ? 'positive' : 'negative'
    },
    {
      metric: '文件大小',
      current: selectedVersion.value.fileSize,
      compare: compare.fileSize,
      diff: 'N/A',
      diffClass: ''
    }
  ]
})

// 数据生成函数
function generateRandomData(base: number, range: number, count: number) {
  return Array.from({length: count}, (_, i) => ({
    time: `${i+1}`,
    value: base + Math.random() * range
  }))
}

// 处理方法
const handleFilter = () => {
  currentPage.value = 1 // 重置到第一页
  ElMessage.success('查询成功')
}

const resetFilter = () => {
  filterForm.value = {
    modelType: '',
    dateRange: []
  }
  currentPage.value = 1
  ElMessage.success('已重置筛选条件')
}

const showVersionDetail = (row: any) => {
  selectedVersion.value = row
  compareVersion.value = ''
  detailDialogVisible.value = true
}

const handleRowClick = (row: any) => {
  showVersionDetail(row)
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除版本 ${row.version} 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = rawVersionsData.value.findIndex(v => v.version === row.version)
    if (index !== -1) {
      rawVersionsData.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消操作
  })
}

const deployVersion = (version: any) => {
  ElMessageBox.confirm(`确定要部署版本 ${version.version} 为当前模型吗?`, '确认部署', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rawVersionsData.value.forEach(v => v.isCurrent = false)
    version.isCurrent = true
    ElMessage.success(`版本 ${version.version} 部署成功`)
    detailDialogVisible.value = false
  }).catch(() => {
    // 取消操作
  })
}

const showUploadDialog = () => {
  uploadDialogVisible.value = true
}

const beforeUpload = (file: any) => {
  const isModelFile = ['.pth', '.h5', '.pt'].some(ext => file.name.endsWith(ext))
  if (!isModelFile) {
    ElMessage.error('只能上传模型文件 (.pth, .h5, .pt)')
    return false
  }
  const isLt500M = file.size / 1024 / 1024 < 500
  if (!isLt500M) {
    ElMessage.error('模型文件大小不能超过500MB')
    return false
  }
  return true
}

const handleUploadSuccess = (response: any, file: any) => {
  uploadForm.value.file = file
}

const submitUpload = () => {
  if (!uploadForm.value.version) {
    ElMessage.error('请输入版本号')
    return
  }

  // 创建新版本
  const newVersion = {
    version: uploadForm.value.version,
    type: uploadForm.value.type,
    accuracy: parseFloat((Math.random() * 10 + 85).toFixed(1)),
    loss: parseFloat((Math.random() * 0.3 + 0.3).toFixed(2)),
    f1Score: parseFloat((Math.random() * 0.1 + 0.85).toFixed(2)),
    createdAt: new Date().toLocaleString(),
    description: uploadForm.value.description,
    isCurrent: false,
    creator: 'admin',
    fileSize: `${(Math.random() * 10 + 40).toFixed(1)}MB`,
    hash: Math.random().toString(36).substring(2, 18)
  }

  // 添加到原始数据
  rawVersionsData.value.unshift(newVersion)

  // 重置表单和对话框
  uploadDialogVisible.value = false
  uploadForm.value = {
    file: null,
    version: '',
    type: 'global',
    description: ''
  }

  ElMessage.success('模型上传成功')
}

const accuracyColor = (accuracy: number) => {
  if (accuracy > 90) return '#67C23A'
  if (accuracy > 80) return '#409EFF'
  return '#E6A23C'
}

const lossColor = (loss: number) => {
  if (loss < 0.4) return '#67C23A'
  if (loss < 0.6) return '#E6A23C'
  return '#F56C6C'
}
</script>

<style scoped>
.versions-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.filter-card {
  margin-bottom: 20px;
}

.versions-list {
  margin-bottom: 20px;
}

.versions-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.versions-table {
  margin-top: 10px;
}

.versions-table :deep(.el-table__row) {
  cursor: pointer;
}

.current-icon {
  margin-left: 5px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.version-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.metrics-container {
  display: grid;
  gap: 16px;
}

.metric-item {
  padding: 10px;
  border-radius: 4px;
  background-color: var(--el-bg-color-page);
}

.metric-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 5px;
}

.metric-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.hash-value {
  font-family: monospace;
  cursor: pointer;
}

.version-description {
  line-height: 1.6;
  white-space: pre-wrap;
}

.compare-select {
  width: 100%;
  margin-bottom: 20px;
}

.comparison-result {
  margin-top: 20px;
}

.comparison-result .positive {
  color: var(--el-color-success);
}

.comparison-result .negative {
  color: var(--el-color-danger);
}

.empty-comparison {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mt-4 {
  margin-top: 1rem;
}

.upload-demo {
  width: 100%;
}
</style>